<template>
  <Dialog v-model="dialogVisible" :title="title" :scroll="true">
    <el-form ref="formRef" v-loading="formLoading" :model="formData" label-width="80px">
      <el-form-item label="等级设置">
        <el-row>
          <template v-if="formData.promoteRule && formData.promoteRule.length > 0">
            <el-col v-for="(item, index) in formData.promoteRule" :key="index" class="mb-10px">
              <span class="font-bold"
                >晋升等级名称:{{
                  list.find((ele) => {
                    return ele.agentLevel == item.agentLevel
                  }).agentLevelName
                }}</span
              >
              <el-button link type="danger" @click="deletePromoteRule(index)"> 删除 </el-button>
              <el-row>
                <el-col class="mb-10px">
                  升级规则：
                  <el-button :disabled="formLoading" type="primary" @click="add(item)"
                    >新增规则</el-button
                  >
                </el-col>

                <el-col v-for="(ele, eleIndex) in item.promoteRule" :key="eleIndex" class="flex">
                  <div class="flex items-center">
                    <span class="font-bold">规则{{ eleIndex + 1 }}</span>
                    <el-button link type="danger" @click="deleteRule(item.promoteRule, eleIndex)">
                      删除
                    </el-button>
                  </div>
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="推荐:">
                        <el-select
                          class="!w-100%"
                          v-model="ele.agentLevelFrom"
                          clearable
                          placeholder="请选择推荐等级"
                        >
                          <el-option
                            :label="item.agentLevelName"
                            :value="item.agentLevel"
                            v-for="(item, index) in ruleLevellist"
                            :key="index"
                          />
                        </el-select> </el-form-item
                    ></el-col>
                    <el-col :span="12">
                      <el-form-item label="满:" label-width="40px">
                        <el-input-number
                          v-model="ele.num"
                          :min="0"
                          :max="100"
                          :precision="0"
                          :controls="false"
                          class="!w-100%"
                          placeholder="推荐人数"
                        >
                          <template #suffix> 人 </template>
                        </el-input-number>
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <!-- <div> -->
                  <el-tag type="warning">
                    推荐{{ ele.agentLevelFrom || 'X' }}等级,满{{
                      ele.num || 'X'
                    }}人即可升级。</el-tag
                  >
                  <!-- </div> -->
                </el-col>
              </el-row>
            </el-col>
          </template>
          <el-col :span="24">
            <el-button :disabled="formLoading" type="primary" @click="addLevel"
              >添加代理等级</el-button
            >
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <Dialog v-model="levelDialogVisible" :title="'选择要晋升的等级'" :scroll="false">
    <el-form-item label="代理等级" prop="agentLevel">
      <el-select v-model="agentLevel" clearable placeholder="请选择代理等级">
        <el-option
          :label="item.agentLevelName"
          :disabled="
            !isEmpty(
              formData.promoteRule.find((ele) => {
                return ele.agentLevel == item.agentLevel
              })
            )
          "
          :value="item.agentLevel"
          v-for="(item, index) in list"
          :key="index"
        />
      </el-select>
    </el-form-item>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitSelectForm">确 定</el-button>
      <el-button @click="levelDialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import * as LevelApi from '@/api/mall/trade/agent/level'
import { isEmpty } from '@/utils/is'

/** 修改上级代理商表单 */
defineOptions({ name: 'UpdateBindUserForm' })
interface promoteRuleItemType {
  promoteRule: { levelName: string | undefined; level: number | undefined; num: number }[]
  levelName: string | undefined
  level: number | undefined
}

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用

const title = ref('')

const formData = ref<any>({
  promoteRule: [] as promoteRuleItemType[]
})

const dialogVisible = ref(false) // 弹窗的是否展示
const levelDialogVisible = ref(false)
const agentLevel = ref<any>(undefined)
const addLevel = () => {
  agentLevel.value = undefined
  levelDialogVisible.value = true
}
const closeAddLevel = () => {
  levelDialogVisible.value = false
}
const add = (item) => {
  if (item.promoteRule) {
    item.promoteRule.push({
      num: 1,
      agentLevelFrom: undefined
    })
  } else {
    item.promoteRule = []
    item.promoteRule.push({
      num: 1,
      agentLevelFrom: undefined
    })
  }
}

const submitSelectForm = () => {
  let slelectLeveal = list.value.find((ele) => {
    return ele.agentLevel == agentLevel.value
  })
  formData.value.promoteRule.push({
    agentLevel: slelectLeveal.agentLevel,
    promoteRule: []
  })
  closeAddLevel()
}
/** 删除优惠规则 */
const deletePromoteRule = (ruleIndex: number) => {
  formData.value.promoteRule.splice(ruleIndex, 1)
}
const deleteRule = (ruleList: any, ruleIndex: number) => {
  ruleList.splice(ruleIndex, 1)
}
// const objectToArray = (obj) => {
//   if (!obj) {
//     return []
//   } else {
//     return Object.keys(obj).map(function (key) {
//       return { level: key, reward: obj[key] }
//     })
//   }
// }
// const arrayToObject = (arr) => {
//   return arr.reduce(function (obj, item) {
//     obj[item.level] = item.reward
//     return obj
//   }, {})
// }

const level = ref()
const list = ref<any>([]) // 可选择升级等级的数据

const ruleLevellist = ref<any>([]) //可选择的规则等级列表
/** 打开弹窗 */
const open = async (levelInfo, levelList) => {
  // 反显上级代理商
  title.value = '设置' + levelInfo.agentLevelName + '升级规则'
  level.value = await LevelApi.getLevel(levelInfo.agentLevelId)
  formData.value.promoteRule = level.value.promoteRule
  ruleLevellist.value = levelList
  list.value = levelList.filter((ele: any) => {
    return ele.agentLevel > level.value.agentLevel
  })

  dialogVisible.value = true
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
const message = useMessage() // 消息弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
/** 修改上级代理商 */
const submitForm = async () => {
  // 发送操作成功的事件

  const data = { agentLevelId: level.value.agentLevelId } as unknown as LevelApi.LevelVO

  data.promoteRule = formData.value.promoteRule
  await LevelApi.updateLevel(data)
  message.success('设置成功')
  emit('success')
  dialogVisible.value = false
}
</script>
